using HBFramework;
using UnityEngine;
using UnityEngine.UI;

public class Panel_Setting : BasePanel
{
    public override int RemainTime => 10;

    public override int Layer => 1;

    public override string Path => "ui/panel_setting";

    private Animation anim;
    private ToggleComp soundToggle;
    private ToggleComp effectToggle;
    private ToggleComp vibrateToggle;
    private Button closeBtn;

    public override void OnInit(GameObject ui)
    {
        anim = ui.GetComponent<Animation>();
        var toggle_sound = ui.transform.Find("root_popup/root_sound/toggle").gameObject;
        soundToggle = new ToggleComp(toggle_sound, OnSoundVolumeChanged);
        var toggle_effect = ui.transform.Find("root_popup/root_effect/toggle").gameObject;
        effectToggle = new ToggleComp(toggle_effect, OnEffectVolumeChanged);
        var toggle_vibrate = ui.transform.Find("root_popup/root_vibrate/toggle").gameObject;
        vibrateToggle = new ToggleComp(toggle_vibrate);
        closeBtn = ui.transform.Find("root_popup/btn_close").GetComponent<Button>();
        closeBtn.onClick.AddListener(OnCloseBtnClick);

        ButtonAnimComp closeBtnAnim = new(closeBtn);
    }

    public override void OnRelease()
    {
        closeBtn.onClick.RemoveListener(OnCloseBtnClick);
    }

    public override void OnShow()
    {
        anim.Play();
        var settingStorage = StorageManager.Instance.GetStorage<SettingStorage>();
        soundToggle.IsOn = settingStorage.openSound;
        effectToggle.IsOn = settingStorage.openSoundEffect;
        vibrateToggle.IsOn = settingStorage.openVibrate;
    }

    public override void OnHide()
    {
        SaveVolume();
    }

    private void SaveVolume()
    {
        var settingStorage = StorageManager.Instance.GetStorage<SettingStorage>();
        settingStorage.openSound = soundToggle.IsOn;
        settingStorage.openSoundEffect = effectToggle.IsOn;
        settingStorage.openVibrate = vibrateToggle.IsOn;
        StorageManager.Instance.SaveStorage<SettingStorage>();
    }

    private void OnSoundVolumeChanged(bool open)
    {
        if (open)
            AudioManager.Instance.MusicVolume = 100;
        else
            AudioManager.Instance.MusicVolume = 0;
    }

    private void OnEffectVolumeChanged(bool open)
    {
        if (open)
            AudioManager.Instance.SoundVolume = 100;
        else
            AudioManager.Instance.SoundVolume = 0;
    }

    private void OnCloseBtnClick()
    {
        PanelManager.Instance.ClosePanel<Panel_Setting>();
    }
}
